﻿#region Using directives
using System;
using System.Web.UI;
using ProcolDemo.AICore;
using ProcolDemo.ProjectsReference;
//using ProcolDemo.ProjectUpdates;
using System.Web.UI.WebControls;
using ProcolDemo.User;

#endregion

namespace ProcolDemo
{
    public partial class Projects : Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

            if (!Common.IsUserLoggedIn(Session))
                Response.Redirect("Default.aspx");
            Common.FillI18NStrings(this, Session);

            /* VARIABLES INITIALIZATION */
            ProjectService projectsService = new ProjectService();
            UserService userService = new UserService();
            int userId = Common.GetUserId(Session);
            int userRole = userService.GetUserRole(userId);
            userRoleField.Value = userRole + "";
            String op = Request.QueryString["op"];
            if (op == null) op = "";

            /* INITIALLY HIDDEN SECTIONS */
            results.Visible = false;
            projectInfo.Visible = false;
            editProject.Visible = false;
            displayComments.Visible = false;
            searchForTag.Visible = false;
            projectFilesDiv.Visible = false;
            projectMembersDiv.Visible = false;

            /* POPULATE TAGS SIDEBAR */
            ProjectTagBean[] projectTags = projectsService.getProjectTags();
            ProjectTagsSidebar.DataSource = projectTags;
            ProjectTagsSidebar.DataBind();

            /* DISPLAY PROJECT'S INFORMATION */
            if (op.Equals("projectInfo"))
            {
                int projectId;
                var matchingService = new MatchingService();
                if (!Int32.TryParse(Request.QueryString["projectId"], out projectId))
                    projectId = 0;
                projectInfo.Visible = true;
                displayComments.Visible = true;
                projectFilesDiv.Visible = true;
                projectMembersDiv.Visible = true;
                results.Visible = false;
                searchProject.Visible = false;
                myProjects.Visible = false;
                star1.Visible = false;
                star2.Visible = false;
                star3.Visible = false;
                star4.Visible = false;
                star5.Visible = false;
                
                similarProjects.Visible = true;
                dataSimilarProjects.DataSource = matchingService.GetSimilarProjects(projectId, 10);
                dataSimilarProjects.DataBind();
                
                ProjectBean project = projectsService.GetProject(projectId);
                displayProject_projectName.Text = project.name;
                displayProject_projectCategory.Text = project.category;
                displayProject_projectOwner.Text = project.ownersName;
                userProfileLink.NavigateUrl = "ViewProfile.aspx?Uid=" + project.userId;
                userProfileLink2.NavigateUrl = "ViewProfile.aspx?Uid=" + project.tutorId;
                displayProject_projectCreationDate.Text = project.dateCreated.Day + "/" +
                        project.dateCreated.Month + "/" + project.dateCreated.Year;
                displayProject_projectTags.Text = project.tags;
                displayProject_projectDescription.Text = project.description;
                displayProject_tutorName.Text = userService.GetUserName(project.tutorId);
                if (project.rating >= 1) star1.Visible = true;
                if (project.rating >= 2) star2.Visible = true;
                if (project.rating >= 3) star3.Visible = true;
                if (project.rating >= 4) star4.Visible = true;
                if (project.rating >= 5) star5.Visible = true;
                if (project.status == 1) displayProject_statusText.Text = "Active and available";
                if (project.status == 2) displayProject_statusText.Text = "Active and closed";
                if (project.status == 3) displayProject_statusText.Text = "Inactive and available";
                if (project.status == 4) displayProject_statusText.Text = "Inactive and closed";
                if (projectsService.isOwner(userId, projectId)) isOwner.Value = "true";
                if (userService.isPartOfProject(userId, projectId)) isPartOfProject.Value = "true";
                if (userService.isTutorOfProject(userId, projectId)) isTutorField.Value = "true";
                projectStatusField.Value = project.status + "";
                editProjectLink.NavigateUrl = "Projects.aspx?op=editProject&projectId=" + projectId;
                ProjectCommentBean[] commentsList = projectsService.GetListOfProjectsComments(projectId);
                if (commentsList.Length == 0)
                    noComments.InnerHtml = "<center>There are no comments.</center><br /> <br />";
                else
                {
                    displayProjectsComments.DataSource = commentsList;
                    displayProjectsComments.DataBind();
                }

                subscribeLink.HRef = String.Format("http://localhost:1059/RssGenerator.aspx?type=projects&Uid={0}&id={1}", userId, projectId);
            }

            /* EDIT AN IDEA'S INFORMATION */
            else if (op.Equals("editProject"))
            {
                int projectId;
                if (!Int32.TryParse(Request.QueryString["projectId"], out projectId))
                    projectId = 0;
                editProject.Visible = true;
                results.Visible = false;
                searchProject.Visible = false;
                myProjects.Visible = false;
                ProjectBean project = projectsService.GetProject(projectId);
                projectIdHidden.Text = project.projectId.ToString();
                editProject_projectName.Text = project.name.TrimEnd();
                editProject_projectCategory.Text = project.category.TrimEnd();
                editProject_projectDescription.Text = project.description.TrimEnd();
                if (project.tags != null)
                    editProject_projectTags.Text = project.tags.TrimEnd();
                int[] tutors = userService.GetListOfTeachers();
                for (int i = 0; i < tutors.Length; i++)
                {
                    editProjectTutorId.Items.Add(new ListItem(userService.GetUserName(tutors[i]), tutors[i] + ""));
                }
            }

            /* SEARCH FOR TAG */
            else if (op.Equals("tag"))
            {
                int idTag;
                if (!Int32.TryParse(Request.QueryString["idTag"], out idTag))
                    idTag = 0;
                searchForTag.Visible = true;
                projectInfo.Visible = false;
                displayComments.Visible = false;
                results.Visible = false;
                searchProject.Visible = false;
                myProjects.Visible = false;
                ProjectBean[] projectsWithTag = projectsService.searchForTag(idTag);
                searchForTagTable.DataSource = projectsWithTag;
                searchForTagTable.DataBind();
                searchForTag_TagName.Text = projectsService.getTagName(idTag);
            }

            /* DISPLAY MY PROJECTS */
            ProjectBean[] projectsList = projectsService.GetListOfProjectsByUserId(Common.GetUserId(Session));
            for (int i = 0; i < projectsList.Length; i++)
                if (projectsList[i].nameLength > 65)
                    projectsList[i].name = projectsList[i].name.Substring(0, 64) + "...";
            ShowMyProjects.DataSource = projectsList;
            ShowMyProjects.DataBind();

            /* SET MAXIMUM RESULTS FOR AUTOCOMPLETE SEARCH FIELD */
            txtSearch_AutoCompleteExtender.CompletionSetCount = 10;
        }

        /* SIMPLE SEARCH BUTTON */
        protected void SimpleSearch_Click(object sender, EventArgs e)
        {
            ProjectService projectsService = new ProjectService();

            //if (String.IsNullOrEmpty(txtSearch.Text))
            results.Visible = true;
            searchProject.Visible = true;
            myProjects.Visible = false;

            ProjectBean[] projectsList = projectsService.GetListOfProjectsByKeyword(txtSearch.Text);
            for (int i = 0; i < projectsList.Length; i++)
                if (projectsList[i].nameLength > 75)
                    projectsList[i].name = projectsList[i].name.Substring(0, 74) + "...";

            for (int i = 0; i < projectsList.Length; i++)
                switch (projectsList[i].status)
                {
                    case 1: projectsList[i].statusText = "Activo y disponible"; break;
                    case 2: projectsList[i].statusText = "Activo y cerrado"; break;
                    case 3: projectsList[i].statusText = "Inactivo y disponible"; break;
                    case 4: projectsList[i].statusText = "Inactivo y cerrado"; break;
                }
            ShowResults.DataSource = projectsList;
            ShowResults.DataBind();
        }

        protected void txtSearch_TextChanged(object sender, EventArgs e)
        {
        }

        /* UPLOAD FILE */
        protected void ButtonFileUpload_Click(object sender, EventArgs e)
        {
            if (FileUpload.HasFile)
                try
                {
                    FileUpload.SaveAs("C:\\MEDIA\\Mexico\\Studium\\AdvancedInternet\\Project\\LastVersion\\ProcolDemo\\UploadFiles\\" +
                         FileUpload.FileName);
                    lblFileUpload.Text = "File name: " +
                         FileUpload.PostedFile.FileName + "<br>" +
                         FileUpload.PostedFile.ContentLength + " kb<br>" +
                         "Content type: " +
                         FileUpload.PostedFile.ContentType;
                }
                catch (Exception ex)
                {
                    lblFileUpload.Text = "ERROR: " + ex.Message.ToString();
                }
            else
            {
                lblFileUpload.Text = "You have not specified a file.";
            }
        }

        /*protected void Button1_Click(object sender, EventArgs e)
        {
            ProjectService projectService = new ProjectService();
            byte status = 1;
            int projectId = projectService.AddNewProject(Common.GetUserId(Session), newProject_projectDescription.Text, status, DateTime.Now, newProject_projectName.Text, newProject_projectCategory.Text, newProject_projectTags.Text);
            ProjectUpdatesService createProjectUpdate = new ProjectUpdatesService();
            createProjectUpdate.AddProjectUpdate("Se ha agregado una project.", projectId, Common.GetUserId(Session), 0, DateTime.Now);
            CollapsiblePanelExtender2.Collapsed = true;
        }

        public void deleteProject_Click(object sender, CommandEventArgs e)
        {
            int projectId = System.Convert.ToInt32(e.CommandArgument.ToString());
            ProjectsService projectService = new ProjectsService();
            projectService.LogicDeleteProject(projectId);
            ProjectUpdatesService createProjectUpdate = new ProjectUpdatesService();
            createProjectUpdate.AddProjectUpdate("Se ha eliminado una project.", projectId, Common.GetUserId(Session), 0, DateTime.Now);
        }

        protected void editProject_OKButton_Click(object sender, EventArgs e)
        {
            ProjectsService projectService = new ProjectsService();
            int projectsId = Int32.Parse(projectIdHidden.Text);
            projectService.UpdateProjectRecord(projectsId, editProject_projectDescription.Text, editProject_projectName.Text, editProject_projectCategory.Text, editProject_projectTags.Text);
            ProjectUpdatesService createProjectUpdate = new ProjectUpdatesService();
            createProjectUpdate.AddProjectUpdate("Se ha actualizado una project.", projectsId, Common.GetUserId(Session), 0, DateTime.Now);
            editProject.Visible = false;
            results.Visible = false;
            searchProject.Visible = true;
            newProject.Visible = true;
            myProjects.Visible = true;
        }*/



    }
}